﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using snat.model;
using snat.algorithms;
using System.IO;

namespace algorithms.algorithms.Metrics
{
    public class AverageNodeDegree : IAlgorithm, ITextRenderable, IReaderWriter {

        public double NodeDegree { get; private set; }
        public double InNodeDegree { get; private set; }
        public double OutNodeDegree { get; private set; }

        private void Process() {
            NodeDegree = NetworkModel.Instance.Nodes.Values.Average(e => e.Degree);
            InNodeDegree = NetworkModel.Instance.Nodes.Values.Average(e => e.InDegree);
            OutNodeDegree = NetworkModel.Instance.Nodes.Values.Average(e => e.OutDegree);
            if(RenderText != null) RenderText(this);
        }

        public string Name {
            get { return "Average Node Degree"; }
        }

        public void Register() {
            NetworkModel.Instance.TapeEnded += Process;
        }

        public void DeRegister() {
            NetworkModel.Instance.TapeEnded -= Process;
        }

        public event RenderTextDelegate RenderText;
        
        public string GetRenderableText() {
            return String.Format("Average Degree: {0}\nAverage In Degree: {1}\nAverage Out Degree: {2}",
                NodeDegree, InNodeDegree, OutNodeDegree);
        }

        public void Write(string filePath) {
            using (StreamWriter output = new StreamWriter(filePath)) {
                output.WriteLine(GetRenderableText());
            }
        }

        public string Read(string filePath) {
            String ret = String.Empty;
            using (StreamReader input = new StreamReader(filePath)) {
                ret += input.ReadLine();
            }
            return ret;
        }
    }
}
